<template>
  <div class="gallery-container">
    <div class="gallery-header">
      <h2>我的图库</h2>
      <div class="gallery-filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索图片"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="selectedTags"
          multiple
          placeholder="选择标签"
          clearable
        >
          <el-option
            v-for="tag in tags"
            :key="tag.value"
            :label="tag.label"
            :value="tag.value"
          />
        </el-select>
      </div>
    </div>

    <div v-loading="loading" class="gallery-content">
      <el-empty v-if="!loading && photos.length === 0" description="暂无图片" />

      <el-row v-else :gutter="20">
        <el-col
          v-for="photo in filteredPhotos"
          :key="photo.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card class="photo-card" :body-style="{ padding: '0px' }">
            <div class="photo-wrapper">
              <el-image
                :src="photo.url"
                fit="cover"
                :preview-src-list="[photo.url]"
                @error="handleImageError"
                loading="lazy"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                    <span class="error-url">{{ photo.url }}</span>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="photo-info">
              <div class="photo-title">图片 {{ photo.id }}</div>
              <div class="photo-tags">
                <el-tag
                  v-for="tag in photo.tags"
                  :key="tag"
                  size="small"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="photo-meta">
                <span>{{ formatDate(photo.date) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import { Search, Picture } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";

// 定义照片类型接口
interface Photo {
  id: number;
  url: string;
  date: string;
  tags: string[];
}

// 处理图片URL，确保是完整的URL
const getFullImageUrl = (url: string): string => {
  if (!url) return "";
  if (url.startsWith("http")) return url;
  // 确保路径格式正确，移除多余的斜杠
  const cleanPath = url.replace(/^\/+|\/+$/g, "");
  return `http://localhost:3000/${cleanPath}`;
};

const loading = ref(false);
const photos = ref<Photo[]>([]);
const searchQuery = ref("");
const selectedTags = ref<string[]>([]);

// 标签选项
const tags = [
  { label: "🏞️ 风景", value: "landscape" },
  { label: "👤 人物", value: "portrait" },
  { label: "🏗️ 建筑", value: "architecture" },
  { label: "🍔 美食", value: "food" },
  { label: "🚗 交通工具", value: "vehicle" },
  { label: "🎨 艺术", value: "art" },
];

// 处理图片加载错误
const handleImageError = (e: Event) => {
  const imgElement = e.target as HTMLImageElement;
  console.error("图片加载失败:", {
    src: imgElement.src,
    error: e,
  });
  ElMessage.error(`图片加载失败: ${imgElement.src}`);
};

// 获取照片列表
const fetchPhotos = async () => {
  loading.value = true;
  try {
    const response = await axios.get<Photo[]>("http://localhost:3000/images", {
      params: {
        userId: 1,
      },
    });

    if (response.data) {
      // 确保每个图片URL都是完整的
      photos.value = response.data.map((photo) => {
        const fullUrl = getFullImageUrl(photo.url);
        console.log("处理图片URL:", {
          original: photo.url,
          processed: fullUrl,
        });
        return {
          ...photo,
          url: fullUrl,
        };
      });
      console.log("成功获取照片列表:", photos.value);
    }
  } catch (error: any) {
    console.error("获取照片列表失败:", error);
    if (error.response) {
      ElMessage.error(
        `服务器错误: ${error.response.data.message || error.response.status}`
      );
    } else if (error.request) {
      ElMessage.error("无法连接到服务器，请确保后端服务正在运行");
    } else {
      ElMessage.error("获取照片列表失败: " + error.message);
    }
  } finally {
    loading.value = false;
  }
};

// 搜索照片
const searchPhotos = async (tag: string) => {
  loading.value = true;
  try {
    const response = await axios.get<Photo[]>(
      "http://localhost:3000/images/search",
      {
        params: {
          userId: 1,
          tag: tag,
        },
      }
    );

    if (response.data) {
      photos.value = response.data.map((photo) => {
        const fullUrl = getFullImageUrl(photo.url);
        console.log("处理搜索图片URL:", {
          original: photo.url,
          processed: fullUrl,
        });
        return {
          ...photo,
          url: fullUrl,
        };
      });
    }
  } catch (error: any) {
    console.error("搜索照片失败:", error);
    ElMessage.error("搜索照片失败");
  } finally {
    loading.value = false;
  }
};

// 监听标签选择变化
watch(selectedTags, (newTags) => {
  if (newTags.length > 0) {
    searchPhotos(newTags[0]); // 使用第一个选中的标签进行搜索
  } else {
    fetchPhotos(); // 如果没有选中标签，获取所有照片
  }
});

// 监听搜索关键词变化
watch(searchQuery, (newQuery) => {
  if (newQuery) {
    // 如果搜索框有内容，使用标签搜索
    searchPhotos(newQuery);
  } else {
    // 如果搜索框为空，获取所有照片
    fetchPhotos();
  }
});

// 过滤照片
const filteredPhotos = computed(() => {
  return photos.value.filter((photo) => {
    const matchesSearch = photo.tags.some((tag) =>
      tag.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
    const matchesTags =
      selectedTags.value.length === 0 ||
      selectedTags.value.some((tag) => photo.tags.includes(tag));
    return matchesSearch && matchesTags;
  });
});

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
};

// 在组件挂载时获取照片列表
onMounted(() => {
  fetchPhotos();
});
</script>

<style scoped>
.gallery-container {
  padding: 20px;
}

.gallery-header {
  margin-bottom: 24px;
}

.gallery-header h2 {
  margin: 0 0 16px 0;
  font-size: 24px;
  color: #333;
}

.gallery-filters {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.search-input {
  width: 300px;
}

.gallery-content {
  min-height: 400px;
}

.photo-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.photo-card:hover {
  transform: translateY(-5px);
}

.photo-wrapper {
  height: 200px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.photo-wrapper .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-error {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
  gap: 8px;
  padding: 16px;
  text-align: center;
}

.image-error span {
  font-size: 14px;
}

.error-url {
  font-size: 12px !important;
  color: #f56c6c;
  word-break: break-all;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.photo-info {
  padding: 12px;
}

.photo-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.photo-tags {
  margin-bottom: 8px;
}

.photo-tags .tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.photo-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}
</style>
